const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

// 中间件
app.use(express.json());
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Content-Type', 'application/json;charset=utf-8');
  next();
});

// 内存数据库
let users = [{ id: 1, username: 'testuser', password: '123456' }];
let products = Array.from({length: 100}, (_,i) => ({
  id: i+1,
  name: `商品${i+1}`,
  price: Math.random()*1000,
  category: ['电子','服饰','家居'][i%3],
  cover: `https://example.com/img/${i+1}.jpg`
}));
let carts = {};
let addresses = [{
  id: 1,
  receiver: '张三',
  phone: '13800138000',
  address: '北京市朝阳区'
}];

// 路由配置
const router = express.Router();

// 用户模块
router.post('/login', (req, res) => {
  const {username, password} = req.body;
  const user = users.find(u => u.username === username && u.password === password);
  if (!user) return res.status(401).json({ code: 401, message: '认证失败' });
  
  const token = jwt.sign({ userId: user.id }, 'secret_key', { expiresIn: '1h' });
  res.json({
    code: 200,
    data: {
      token,
      userInfo: { userId: user.id, username: user.username }
    }
  });
});

// 商品模块
router.get('/products', (req, res) => {
  const { page = 1, size = 10, category } = req.query;
  let filtered = category 
    ? products.filter(p => p.category === category)
    : products;

  const start = (page - 1) * size;
  const end = start + parseInt(size);
  
  res.json({
    code: 200,
    data: {
      total: filtered.length,
      list: filtered.slice(start, end)
    }
  });
});

// 购物车模块
router.post('/cart/add', (req, res) => {
  const { productId, quantity } = req.body;
  const userId = req.headers.authorization?.split(' ')[1];
  
  if (!carts[userId]) carts[userId] = [];
  carts[userId].push({
    cartItemId: Date.now(),
    productId,
    quantity
  });

  res.json({
    code: 200,
    data: {
      cartItemId: Date.now(),
      totalItems: carts[userId].length
    }
  });
});

// 地址模块
router.get('/address', (req, res) => {
  res.json({
    code: 200,
    data: addresses
  });
});

app.use('/api', router);

app.listen(3000, () => {
  console.log('Server running on port 3000');
});